import { createStore } from 'vuex';

export default createStore({
  state: {
    token: localStorage.getItem('token'),
    role:  localStorage.getItem('role'),
  },
  getters: {
    isAuthenticated: state => !!state.token,
    isAdmin: state => state.role === "admin",
  },
  mutations: {
    setState(state, data) {
      state.token = data.token;
      state.role=data.role;
      localStorage.setItem('token', data.token);
      localStorage.setItem('role', data.role);
      setTimeout(() => {
        localStorage.removeItem('token');
        localStorage.removeItem('role');
      }, 1000*60*60*24);
    },
    clearState(state) {
      state.token = '';
      state.role='';
      localStorage.removeItem('token');
      localStorage.removeItem('role');
    },
  },
  actions: {
    login({ commit }, data) {
      commit('setState', data);
    },
    logout({ commit }) {
      commit('clearState');
    },
  },
  modules: {},
});
